<template>
  <div class="select-witch-input" :class="{'hasInput':hasInput}" >
    <el-select v-model="selectValue" :placeholder="item.placeholder" @change="selectChange(item)">
      <el-option
        v-for="option in item.options"
        :key="option.value"
        :label="option.label"
        :value="option.label">
      </el-option>
    </el-select>
    <el-input v-if="hasInput" v-model="inputValue" :placeholder="inputPlaceholder"></el-input>

    <select-input v-model="curDatas[item.fieldCode]"></select-input>

  </div>
</template>

<script>
import Vue from "vue";
Vue.component("select-input", {
  props: ["value"],
  template: `<input hidden v-on:input="$emit('input', $event.target.value)" v-bind:value="value">`
});

export default {
  name: "SelectInputEdit",
  props: ["item", "curDatas", "curRules"],
  data() {
    return {
      valueDatas: {},
      selectValue: "",
      inputValue: "",
      rules1: {},
      hasInput: false,
      inputPlaceholder: ""
    };
  },
  computed: {
    userInput() {
      return this.curDatas[this.item.fieldCode];
    }
  },
  watch: {
    curDatas: {
      handler(curVal) {
        this.$emit("update:curDatas", curVal);
      },
      deep: true
    },
    curRules: {
      handler(curVal) {
        this.$emit("update:curRules", curVal);
      },
      deep: true
    },
    selectValue: function() {
      this.getValue();
    },
    inputValue: function() {
      this.getValue();
    }
  },
  created: function() {
    this.setValue();
    this.selectChange(this.item);
  },
  methods: {
    setValue() {
      let value = this.curDatas[this.item.fieldCode];
      this.selectValue = value[0];
      this.inputValue = value[1];
      this.hasInput = value[1] != null ? true : false;
    },
    getValue() {
      if (this.inputValue) {
        this.curDatas[this.item.fieldCode] = [
          this.selectValue,
          this.inputValue
        ];
      } else {
        this.curDatas[this.item.fieldCode] = [this.selectValue];
      }
    },
    selectChange(item) {
      let label = this.selectValue;
      if (label != undefined) {
        item.options.forEach(o => {
          if (o.label === label) {
            this.hasInput = o.hasInput;
            this.inputPlaceholder = o.placeholder;
            if (o.hasInput) {
              this.curRules[item.fieldCode][0].fields["1"].required = true;
              $("#" + item.fieldCode)
                .find(".el-form-item__error")
                .show();
              $("#" + item.fieldCode).removeClass("is-success");
            } else {
              this.inputValue = null; //删除输入框内容

              this.curRules[item.fieldCode][0].fields["1"].required = false;
              $("#" + item.fieldCode)
                .find(".el-form-item__error")
                .hide();
              $("#" + item.fieldCode).addClass("is-success");
            }
          }
        });
      }
    }
  }
};
</script>
